package com.thejoyrun.retrofit.http;

import com.google.gson.Gson;
import com.thejoyrun.retrofit.http.Interceptor.ErrorHandleInterceptor;
import com.thejoyrun.retrofit.http.Interceptor.HeaderInterceptor;
import com.thejoyrun.retrofit.http.Interceptor.LogInterceptor;

import gson.GsonHelper;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.JoyrunConverterFactory;
import rx.schedulers.Schedulers;

/**
 * Created by kkmike999 on 2016/5/8.
 *
 * rerofit封装基类
 */
public abstract class BaseRetrofit {

	public <T> T create(Class<T> clazz) {
		OkHttpClient.Builder builder = getOkHttpBuilder();

		// 网络日志输出，在最后加，数据一返回就会输出。关于拦截器参考 http://www.tuicool.com/articles/Uf6bAnz
		builder.addInterceptor(new LogInterceptor());

		Gson gson = GsonHelper.getGson();

		Retrofit retrofit = new Retrofit.Builder().baseUrl(getBaseUrl())
		                                          .client(builder.build())
		                                          .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
		                                          .addConverterFactory(JoyrunConverterFactory.create(gson))
		                                          .build();

		return retrofit.create(clazz);
	}

	/**
	 * 1.单元测试时，重写此方法，避开android引用.
	 * 2.重写此方法，添加更多Intertor
	 *
	 * @return
	 */
	protected OkHttpClient.Builder getOkHttpBuilder() {
		return new OkHttpClient.Builder().cookieJar(new CookieManager())
		                                 .addInterceptor(new HeaderInterceptor())
		                                 .addInterceptor(new ErrorHandleInterceptor());
	}

	protected abstract String getBaseUrl();
}
